package com.huadao.cart_ccs.data.source.http;

import android.util.Log;

import com.huadao.cart_ccs.common.ProgressDialogHandler;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

public abstract class BaseObserver<T> implements Observer<T> {
    private static final String TAG="BaseObserver";

    protected abstract void onBaseError(Throwable t);

    protected abstract void onBaseNext(T data);

    protected abstract boolean isNeedProgressDialog();

    protected abstract String getLoadingMsg();

    private ProgressDialogHandler mProgressDialogHandler;
    private BaseImpl mBaseImpl;
    private Platform mPlatform;

    public BaseObserver(BaseImpl mBaseImpl) {
        this.mBaseImpl = mBaseImpl;
        if(null!=mBaseImpl){
            if(null==mProgressDialogHandler){
                mProgressDialogHandler=new ProgressDialogHandler(mBaseImpl.getContext(),true);
            }
        }
        mPlatform=Platform.get();
    }

    private void showProgressDialog() {
        if (mProgressDialogHandler != null) {
            mProgressDialogHandler.obtainMessage(ProgressDialogHandler.SHOW_PROGRESS_DIALOG, getLoadingMsg()).sendToTarget();
        }
    }

    private void dismissProgressDialog() {
        if (mProgressDialogHandler != null) {
            mProgressDialogHandler.obtainMessage(ProgressDialogHandler.DISMISS_PROGRESS_DIALOG).sendToTarget();
            mProgressDialogHandler = null;
        }
    }

    @Override
    public void onSubscribe(Disposable d) {
        if(mBaseImpl==null||!mBaseImpl.isViewAttached()){
            return;
        }
        //显示进度条
        if (isNeedProgressDialog()) {
            showProgressDialog();
        }
        if (null != mBaseImpl) {
            if (null != d) {
                mBaseImpl.addDisposable(d);
            }
        }
    }

    @Override
    public void onNext(final T t) {
        Log.d(TAG,"http is on next");
        if(mBaseImpl==null||!mBaseImpl.isViewAttached()){
            return;
        }
        if(null!=t){
            mPlatform.execute(new Runnable() {
                @Override
                public void run() {
                    onBaseNext(t);
                }
            });
        }
    }

    @Override
    public void onError(final Throwable e) {
        Log.d(TAG,"http is on error");
        if(mBaseImpl==null||!mBaseImpl.isViewAttached()){
            return;
        }
        if(isNeedProgressDialog()){
            dismissProgressDialog();
        }
        mPlatform.execute(new Runnable() {
            @Override
            public void run() {
                onBaseError(e);
            }
        });
    }

    @Override
    public void onComplete() {
        Log.d(TAG,"http is on complete");
        if(mBaseImpl==null||!mBaseImpl.isViewAttached()){
            return;
        }
        if(isNeedProgressDialog()){
            dismissProgressDialog();
        }
    }
}
